package com.teacher.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.teacher.pojo.entity.BedroomLevel;
import com.teacher.pojo.enums.BedroomLevelType;
import com.teacher.pojo.excel.BedroomLevelExcel;
import com.teacher.service.IBedroomLevelService;
import com.teacher.service.IPerStudentService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zfm
 * @Date: 2021/7/30 16:17
 */
public class ExcelBedroomLevelListener extends AnalysisEventListener<BedroomLevelExcel> {
    private Long termId;
    private IBedroomLevelService iBedroomLevelService;

    private List<BedroomLevel> bedroomLevelList = new ArrayList<>();
    private IPerStudentService iPerStudentService;

    public ExcelBedroomLevelListener(Long termId, IBedroomLevelService iBedroomLevelService, IPerStudentService iPerStudentService) {
        this.termId = termId;
        this.iBedroomLevelService = iBedroomLevelService;
        this.iPerStudentService = iPerStudentService;
    }

    @Override
    public void invoke(BedroomLevelExcel bedroomLevelExcel, AnalysisContext analysisContext) {
        if (iPerStudentService.isExit(bedroomLevelExcel.getStudentKey())) {
            BedroomLevel bedroomLevel = new BedroomLevel();
            BeanUtils.copyProperties(bedroomLevelExcel, bedroomLevel);
            bedroomLevel.setTermId(termId);
            bedroomLevel.setLevel(bedroomLevelExcel.getLevel().equals(BedroomLevelType.A.getType()) ? 10
                    : bedroomLevelExcel.getLevel().equals(BedroomLevelType.B.getType()) ? 20 : 30);
            bedroomLevelList.add(bedroomLevel);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        iBedroomLevelService.saveBatch(bedroomLevelList);
    }
}
